package com.sky.wsp.nacos.client.controller;

import com.alibaba.nacos.api.NacosFactory;
import com.alibaba.nacos.api.config.ConfigService;
import com.alibaba.nacos.api.exception.NacosException;
import com.alibaba.nacos.api.naming.NamingFactory;
import com.alibaba.nacos.api.naming.NamingService;
import com.alibaba.nacos.api.naming.pojo.Instance;
import com.sky.wsp.nacos.client.config.RedisProperties;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.List;
import java.util.Properties;

@RestController
public class IndexController {

    @Resource
    private RedisProperties redisProperties;

    @GetMapping
    @RequestMapping("/")
    public String index() {
        return "从Nacos配置中心获取redis地址: " + redisProperties.getHost() + ":" + redisProperties.getPort();
    }

    @GetMapping
    @RequestMapping("/user")
    public String user() {
        return "用户中心";
    }

    @GetMapping
    @RequestMapping("/nacos-info")
    public Properties nacosInfo() {
        String serverAddr = "192.168.36.74:43480";
        String namespace = "DEV";
        String group = "IDAAS_WANG_SHAO_PENG";
        String dataId = "db-mysql.yml";

        Properties properties = new Properties();
        properties.put("serverAddr", serverAddr);
        properties.put("namespace", namespace);
        try {
            ConfigService configService = NacosFactory.createConfigService(properties);
            String config = configService.getConfig(dataId, group, 3000);
            System.out.println(config);
        } catch (NacosException e) {
            e.printStackTrace();
        }

        try {
            NamingService namingService = NamingFactory.createNamingService(properties);
            List<Instance> allInstances = namingService.getAllInstances("my-nacos-client", group);
            allInstances.forEach(i -> System.out.println(i));

//            Instance instance = new Instance();
//            namingService.registerInstance("", instance);
        } catch (NacosException e) {
            e.printStackTrace();
        }
        return properties;
    }
}